<template>
  <div v-loading="loading" class="center-map-wrapper">
    <div id="container"></div>
  </div>
</template>

<script>
import AMapJS from 'amap-js'
import { getEnterpriseMapInfo } from '@/api/bigscreen'
// amap ui类
var PathSimplifier
var DistrictExplorer

// 崂山区域码
const LSADCODE = 370212

export default {
  name: 'centerMap',
  components: {},
  data() {
    return {
      loading: true,
      //
      Amap: null,
      pathSimplifierIns: null,
      districtExplorerIns: null,
      //
      moveInPoints: [],
      moveOutPoints: [],
      markPoints: []
    }
  },
  async mounted() {
    // 初始化加载器
    const amapLoader = new AMapJS.AMapLoader({
      version: '2.0',
      key: 'e07fcac4f7c04a5c807b4dae3d8a5950'
    })
    const amapuiLoader = new AMapJS.AMapUILoader({
      v: '1.1' // UI组件库版本号
    })
    // 加载
    await amapLoader.load()
    await amapuiLoader.load()
    ;[DistrictExplorer, PathSimplifier] = await amapuiLoader.loadUI([
      'geo/DistrictExplorer',
      'misc/PathSimplifier'
    ])

    if (!PathSimplifier.supportCanvas) {
      alert('当前环境不支持 Canvas！')
    }

    this.Amap = new AMap.Map('container', {
      // mapStyle: 'amap://styles/57b73299f4e09142d9ba261a41c5d359',
      // 有背景和省市区标示
      mapStyle: 'amap://styles/b9e71583ba86fe5a9025f13b90bb99f3',
      // 无背景，仅有覆盖物
      // mapStyle: 'amap://styles/fc6e577c67ca54799bff672b8e1d2a79',
      zoom: 4,
      center: [112.562678, 37.873499]
    })
    AMap.plugin('AMap.Scale', () => {
      // 异步加载插件
      var Scale = new AMap.Scale()
      this.Amap.addControl(Scale)
      //
    })

    this.initDistrictExplorer()

    await this.fetchData()
    await this.renderProcess()
  },
  beforeDestroy() {
    // 销毁niceScroll实例，否则滚动条会在其他页面显示
    this.Amap.destroy()
  },
  methods: {
    /**
     * 绘制 path
     * 是否迁出 movein = boolean
     * 坐标集合 pointArr = [x,y][]
     */
    initPathRender(pointArr, movein = true) {
      const pathColor = '#651067'
      // 崂山
      let curPoint = [120.602063, 36.18894]
      let pathData = []

      pointArr.forEach((item) => {
        pathData.push({
          name: movein ? '迁入' : '迁出',
          path: movein
            ? this.getLineFromPoints(item, curPoint)
            : this.getLineFromPoints(curPoint, item)
        })
      })

      this.pathSimplifierIns = new PathSimplifier({
        zIndex: 100,
        // autoSetFitView:false,
        map: this.Amap, // 所属的地图实例
        autoSetFitView: false, // 是否在绘制后自动调整地图视野以适合全部轨迹
        clickToSelectPath: false, // 点击轨迹节点或者轨迹节点间的连线时，选中该轨迹
        data: pathData,
        getPath: function(pathData, pathIndex) {
          return pathData.path
        },
        getHoverTitle: function(pathData, pathIndex, pointIndex) {
          if (pointIndex >= 0) {
            // point
            return pathData.name
          }

          return pathData.name
        },
        renderOptions: {
          pathLineStyle: {
            dirArrowStyle: false
          },
          startPointStyle: {
            radius: 2
          },
          endPointStyle: {
            radius: 2
          },
          pathNavigatorStyle: {
            fillStyle: pathColor
          },
          getPathStyle: function(pathItem, zoom) {
            var lineWidth = Math.round(1 * Math.pow(1.1, zoom - 3))
            return {
              pathLineStyle: {
                strokeStyle: pathColor,
                lineWidth: lineWidth
              },
              pathLineSelectedStyle: {
                lineWidth: lineWidth + 2
              }
            }
          }
        }
      })
      // navg
      for (let i = 0; i < pointArr.length; i++) {
        let distance = Math.sqrt(
          Math.pow(pointArr[i][0] - curPoint[0], 2) +
            Math.pow(pointArr[i][1] - curPoint[1], 2)
        )

        let navg = this.pathSimplifierIns.createPathNavigator(i, {
          loop: true,
          speed: 100000 * distance,
          pathNavigatorStyle: {
            width: 5,
            height: 5,
            // 使用图片
            // content: PathSimplifier.Render.Canvas.getImageContent('./imgs/plane.png', onload, onerror),
            content: 'circle',
            strokeStyle: '#30d9c1',
            fillStyle: '#30d9c1'
            // 经过路径的样式
            // pathLinePassedStyle: {
            //   lineWidth: 6,
            //   strokeStyle: 'black',
            //   dirArrowStyle: {
            //     stepSpace: 15,
            //     strokeStyle: 'red'
            //   }
            // }
          }
        })
        navg.start()
      }
    },
    getLineFromPoints(point1, point2) {
      point1[0] = +point1[0]
      point1[1] = +point1[1]
      point2[0] = +point2[0]
      point2[1] = +point2[1]
      let x_100 = (point2[0] - point1[0]) / 100
      let y_100 = (point2[1] - point1[1]) / 100
      let arr = []
      for (let i = 0; i < 101; i++) {
        let item = [point1[0] + i * x_100, point1[1] + i * y_100]
        arr.push(item)
      }
      return arr
    },
    renderPath(movein = true, time = 5000) {
      return new Promise((resove, reject) => {
        this.initPathRender(
          movein ? this.moveInPoints : this.moveOutPoints,
          movein
        )
        setTimeout(() => {
          this.pathSimplifierIns.clearPathNavigators()
          this.pathSimplifierIns.setData([])
          resove()
        }, time)
      })
    },
    initDistrictExplorer() {
      this.districtExplorerIns = new DistrictExplorer({
        map: this.Amap, // 关联的地图实例
        eventSupport: true // 打开事件支持
      })
      // other:
    },
    async switch2AreaNode(adcode) {
      return new Promise((resove, reject) => {
        this.districtExplorerIns.loadAreaNode(adcode, (error, areaNode) => {
          if (error) {
            console.warn(error)
            // that.tip("获取行政区划地图失败","error")
            reject(error)
            return
          }
          // that.currentAreaNode = window.currentAreaNode = areaNode

          // 设置当前使用的定位用节点
          this.districtExplorerIns.setAreaNodesForLocating([areaNode])
          this.districtExplorerIns.setHoverFeature(null)
          this.renderAreaPolygons(areaNode)

          // 中国中心点
          /* if(adcode == 100000){
            that.Amap.setZoomAndCenter(4,[
              105.3683244,
              39.915085
            ])
          }*/
          resove(areaNode)
        })
      })
    },
    renderAreaPolygons(areaNode) {
      const fillColor = '#ff9900'
      // 更新地图视野
      this.Amap.setBounds(areaNode.getBounds(), null, null, true)
      if (areaNode.getAdcode() === LSADCODE) {
        this.Amap.setZoomAndCenter(11, [120.602063, 36.18894])
      }

      // 清除已有的绘制内容
      this.districtExplorerIns.clearFeaturePolygons()

      const renderFeatuersOptions = {
        cursor: 'default',
        zIndex: 1,
        bubble: true,
        strokeColor: '#000', // 线颜色
        strokeOpacity: 1, // 线透明度
        strokeWeight: 1, // 线宽
        fillColor, // 填充色
        fillOpacity: 0.7 // 填充透明度
      }
      // 绘制子区域
      this.districtExplorerIns.renderSubFeatures(
        areaNode,
        renderFeatuersOptions
      )

      // 绘制父区域
      this.districtExplorerIns.renderParentFeature(
        areaNode,
        renderFeatuersOptions
      )
    },
    renderMarks(points) {
      return new Promise((resolve) => {
        let markers = points.map((per) => {
          return new AMap.Marker({
            position: [per.x, per.y],
            // content: per.entname
          })
        })
        this.Amap.add(markers)

        resolve()
      })
    },
    async renderProcess() {
      await this.renderPath(false)
      await this.renderPath()
      // await this.renderPath(true, 1000 * 60)
      await this.switch2AreaNode(LSADCODE)
      await this.renderMarks(this.markPoints)
    },
    async fetchData() {
      this.loading = true
      try {
        const res = await getEnterpriseMapInfo()
        if (res.resultCode === 200) {
          const data = res.resultData
          this.moveInPoints = data.moveIn.map((per) => {
            return [per.fromY, per.fromX]
          })
          this.moveOutPoints = data.moveOut.map((per) => {
            return [per.toY, per.toX]
          })
          this.markPoints = data.area.slice(0, 400) || []
        }
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    }
  }
}
</script>

<style lang='scss'>
.center-map-wrapper {
  height: 100%;
  #container {
    width: 100%;
    height: 100%;
    margin-bottom: 15px;
  }
}
</style>
